package com.atguigu.gmall.realtime.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Author: tiancy
 * Date: 2021/12/3
 * Desc: 日期工具类
 * SimpleDateFormat存在线程安全问题
 * 使用JDK1.8之后提供的日期相关类进行替代
 * SimpleDateFormat --->DateTimeFormatter
 * Date             --->LocalDateTime
 * Calendar         --->Instant
 */
public class DateTimeUtil {
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //将日期对象转换为字符串日期
    public static String toYmdhms(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return dtf.format(localDateTime);
    }

    //将字符串类型日期转换为时间毫秒数
    public static Long toTs(String dateStr) {
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, dtf);
        Instant instant = localDateTime.toInstant(ZoneOffset.of("+8"));
        return instant.toEpochMilli();
    }


    //获取今天日期,日期格式 `20211210`
    private static Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }

    public static void main(String[] args) {
        System.out.println(ZoneId.systemDefault()); // Asia/Shanghai
    }
}
